<?php defined('SYSPATH') or die('No direct script access.');
class Model_article
{
	//文章阅读排行
	public function read_top($num = 10){
		$r = $this->get_view_record(array('article_id','ip','HTTP_USER_AGENT'));
		//var_dump(MON::as_array($r));
		$read = array();
		foreach ($r as $r){
			if (!isset($r['article_id']) || !strlen($r['article_id'])) continue;
			if (stripos($r['HTTP_USER_AGENT'],'spider') !== false) continue;
			if (stripos($r['HTTP_USER_AGENT'],'googlebot') !== false) continue;
			
			$article_id = (string)$r['article_id'];
			$key = $r['ip'].$r['HTTP_USER_AGENT'];
			if (!isset($read[$article_id])){
				$read[$article_id] = array($key);
				continue;
			}
			if (!in_array($key, $read[$article_id]))
				array_push($read[$article_id], $key);
		}
		//var_dump($read);
		asort($read);
		$read = array_reverse($read);;
		return array_slice($read,0,$num);;
	}
	
	//文章阅读量
	public function read_num($article_id){
		$r = $this->get_view_record(array('_id','ip','HTTP_USER_AGENT'),$article_id);
		return (int)$r->count();
	}
	
	//取得文章阅读记录
	public function get_view_record($field = array(),$article_id = null){
		$o = MON::factory('view_record');
		if (!$field)
			$field = array();
		$HTTP_USER_AGENT = array(
			array('HTTP_USER_AGENT'=>new MongoRegex('/.*spider.*/i')),
			array('HTTP_USER_AGENT'=>new MongoRegex('/.*googlebot.*/i')),
			array('HTTP_USER_AGENT'=>new MongoRegex('/.*msnbot.*/i'))
		);
		if ($article_id === null){
			$r = $o->find(array(
				'ip'=>array('$ne'=>'127.0.0.1'),
				'$nor'=>$HTTP_USER_AGENT
			),$field);
		}else{
			$r = $o->find(array(
				'article_id'=>new MongoId((string)$article_id),
				'ip'=>array('$ne'=>'127.0.0.1'),
				'$nor'=>$HTTP_USER_AGENT
			),$field);
		}
		return $r;
	}
	
	//文章按月排列
	public function doc($num = null){
		$o = MON::factory('article');
		$r = $o->find(array(),array('addTime'));
		$doc = array();
		foreach ($r as $r){
			$month = date('Y-m',$r['addTime']);
			if (isset($doc[$month]))
				$doc[$month][] = $r;
			else
				$doc[$month] = array($r);
		}
		ksort($doc);
		$doc = array_reverse($doc);
		if ($num == null)
			return $doc;
		else
			return array_slice($doc,0,$num);
	}
}